package cn.edu.gdut.deepcode.service.impl;

import cn.edu.gdut.deepcode.component.GlobalIdGenerator;
import cn.edu.gdut.deepcode.config.JwtProperties;
import cn.edu.gdut.deepcode.constant.AbnormalInfoConstant;
import cn.edu.gdut.deepcode.constant.CacheConstant;
import cn.edu.gdut.deepcode.domain.dto.UserDTO;
import cn.edu.gdut.deepcode.domain.po.Result;
import cn.edu.gdut.deepcode.domain.po.User;
import cn.edu.gdut.deepcode.domain.vo.UserVO;
import cn.edu.gdut.deepcode.enums.RoleEnum;
import cn.edu.gdut.deepcode.mapper.UserMapper;
import cn.edu.gdut.deepcode.service.IUserService;
import cn.edu.gdut.deepcode.utils.CommonUtils;
import cn.edu.gdut.deepcode.utils.JwtTool;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static cn.edu.gdut.deepcode.constant.ReqRespConstant.AUTHORIZATION_HEADER_NAME;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @Author: 暮倦
 * @Since: 2025-04-08  21:04
 * @Version: 1.0.0
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final PasswordEncoder passwordEncoder;

    private final JwtTool jwtTool;

    private final JwtProperties jwtProperties;

    private final GlobalIdGenerator globalIdGenerator;


    @Override
    public Result<UserVO> login(UserDTO userDTO, HttpServletResponse response) {
        User user = lambdaQuery()
                .eq(User::getUsername,userDTO.getUsername())
                .one();
        // 用户不存在
        if (BeanUtil.isEmpty(user)) {
            CommonUtils.recordErrorInfoAndThrowException(
                    AbnormalInfoConstant.UL_USER_EI_2,
                    List.of(userDTO,user));
        }

        // 密码错误
        if (!passwordEncoder.matches(
                userDTO.getPassword()+user.getSalty(),
                user.getPassword())) {
            CommonUtils.recordErrorInfoAndThrowException(
                    AbnormalInfoConstant.UL_USER_EI_2,
                    List.of(userDTO,user));
        }
        response.addHeader(AUTHORIZATION_HEADER_NAME,jwtTool.createToken(user.getId(),jwtProperties.getTokenTTL()));
        return Result.success(
                BeanUtil.copyProperties(user,UserVO.class));
    }

    @Override
    public Result<?> register(UserDTO userDTO) {
        Long count = lambdaQuery()
                .eq(User::getUsername, userDTO.getUsername())
                .count();
        if (count!=0){
            CommonUtils.recordErrorInfoAndThrowException(
                    AbnormalInfoConstant.UL_USER_EI_2,
                    List.of(userDTO,count));
        }
        String salty = CommonUtils.generateSalty();
        User user=new User()
                .setId(globalIdGenerator.generate(CacheConstant.GLOBAL_ID_USER_KEY))
                .setUsername(userDTO.getUsername())
                .setPassword(passwordEncoder.encode(userDTO.getPassword()+ salty))
                .setSalty(salty)
                .setRole(RoleEnum.NORMAL_USER);
        save(user);
        return Result.success();
    }
}
